package com.longjianghuasheng.logistics.repository.request

import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.longjianghuasheng.logistics.business.home.NewsResponse
import com.longjianghuasheng.logistics.business.home.ServiceType
import com.longjianghuasheng.logistics.business.home.TypeResponse
import com.longjianghuasheng.logistics.data.model.bean.ApiResponse
import com.longjianghuasheng.logistics.data.model.bean.ApiResponseNoData
import com.longjianghuasheng.logistics.entity.CarInfo
import com.longjianghuasheng.logistics.entity.PictureUrl
import com.longjianghuasheng.logistics.network.apiService
import me.hgj.jetpackmvvm.base.model.BaseModel
import me.hgj.jetpackmvvm.network.AppException
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.lang.Deprecated

/**
 * 作者　: hegaojian
 * 时间　: 2020/5/4
 * 描述　: 处理协程的请求类
 */

val HttpRequestCoroutine: HttpRequestManger by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
    HttpRequestManger()
}

class HttpRequestManger : BaseModel() {


    suspend fun getHome(): NewsResponse {

        val banner = apiService.banner(2)

        if (!banner.isSuccess()) {
            //抛出错误异常
            throw AppException(banner.code, banner.msg)

        }

        val newsList = apiService.news_list(1)



        return newsList.also {
            it.banner = banner.data

            it.type = apiService.service_type(0).data

        }


    }

    suspend fun service_type(): ServiceType {

        val type = apiService.service_type(0)



        if (!type.isSuccess()) {

            //抛出错误异常
            throw AppException(type.code, type.msg)


        }
        type.data.forEach {

            it.types = apiService.service_type(it.id ?: 0).data
        }

        return ServiceType(data = type.data).apply {
            code = 200
            msg = "成功"

            LogUtils.json(this)
//                LogUtils.d("serviceType=$this")
        }
    }

    suspend fun service_list(): ServiceType {


        val type = apiService.service_type(0)



        if (!type.isSuccess()) {

            //抛出错误异常
            throw AppException(type.code, type.msg)


        }
        type.data.forEach {

            it.types = apiService.service_type(it.id ?: 0).data

            it.types.forEach {

                it.types = apiService.service_list2(it.id ?: 0).data.map {

                    TypeResponse(
                        id = it.id,
                        title = it.title,
                        types = mutableListOf()
                    )
                }.toMutableList()

            }
        }



        return ServiceType(data = type.data).apply {
            code = 200
            msg = "成功"

            LogUtils.json(this)
//                LogUtils.d("serviceType=$this")
        }

    }


    //个人信息加图片上传
    suspend fun person_info(
        real_name: String,
        sex: Int,
        tel: String,
        card_no: String,
        card_front: String,
        card_back: String,
    ): ApiResponseNoData {

        val card_frontResponse = image_upload(card_front)
        val card_backResponse = image_upload(card_back)


        if (!card_frontResponse.isSuccess()) {


            throw AppException(card_frontResponse.code, card_frontResponse.msg)
        }
        if (!card_backResponse.isSuccess()) {
            throw AppException(card_backResponse.code, card_backResponse.msg)

        }

        return apiService.people_work(
            real_name,
            sex,
            tel,
            card_no,
            card_frontResponse.data.url,
            card_backResponse.data.url
        )

    }

    suspend fun people_work(
        names: String,
        sex: Int,
        mobile: String,
        card_no: String,
        card_front: String,
        card_back: String,
    ): ApiResponseNoData {

        val card_frontResponse = image_upload(card_front)
        val card_backResponse = image_upload(card_back)


        if (!card_frontResponse.isSuccess()) {


            throw AppException(card_frontResponse.code, card_frontResponse.msg)
        }
        if (!card_backResponse.isSuccess()) {
            throw AppException(card_backResponse.code, card_backResponse.msg)

        }

        return apiService.people_work(
            names,
            sex,
            mobile,
            card_frontResponse.data.url,
            card_backResponse.data.url,
            card_no,
        )

    }

    //上传企业信息
    @Deprecated
    suspend fun company_info(
        real_name: String,
        address: String,
        contact: String,
        tel: String,
        code: String,
        card_front: String
    ): ApiResponseNoData {

        val card_frontResponse = image_upload(card_front)

        if (!card_frontResponse.isSuccess()) {

            throw AppException(card_frontResponse.code, card_frontResponse.msg)
        }

        return apiService.company_info(
            real_name,
            address,
            contact,
            tel,
            code,
            card_frontResponse.data.url
        )

    }

    //车队合作表单
    suspend fun team_work(
        names: String,
        address: String,
        contact: String,
        mobile: String,
        code: String,
        card_front: String,
        card_back: String,
        books: String,
        isCompany: Boolean
    ): ApiResponseNoData {

        val card_frontResponse = image_upload(card_front)


        if (!card_frontResponse.isSuccess()) {


            throw AppException(card_frontResponse.code, card_frontResponse.msg)
        }
        val card_backResponse = image_upload(card_back)

        if (!card_backResponse.isSuccess()) {
            throw AppException(card_backResponse.code, card_backResponse.msg)

        }
        val booksResponse = image_upload(books)

        if (!booksResponse.isSuccess()) {
            throw AppException(booksResponse.code, booksResponse.msg)

        }


        return if (isCompany)
            apiService.company_work(
                names,
                address,
                contact,
                mobile,
                code,
                card_frontResponse.data.url,
                card_backResponse.data.url,
                booksResponse.data.url
            ) else apiService.team_work(
            names,
            address,
            contact,
            mobile,
            code,
            card_frontResponse.data.url,
            card_backResponse.data.url,
            booksResponse.data.url
        )

    }

    //上传头像
    suspend fun avatar(avatar: String): ApiResponseNoData {

        val imageUpload = image_upload(avatar)
        if (!imageUpload.isSuccess()) {


            throw AppException(imageUpload.code, imageUpload.msg)
        }


        return apiService.avatar(imageUpload.data.url)
    }

    //意见反馈
    suspend fun feedback(
        type: Int,
        content: String,
        path: List<String>,
    ): ApiResponseNoData {
        val uploadResult = path.map {

            image_upload(it)
        }

        if (uploadResult.any { !it.isSuccess() }) {
            val imageResult = uploadResult.first { !it.isSuccess() }
            throw AppException(imageResult.code, imageResult.msg)
        }


        return apiService.feedback(type, content, uploadResult.map { it.data.url }.toTypedArray())

    }


    suspend fun driver_work(
        team_id: Int,
        names: String,
        mobile: String,
        code: String,
        card_front: String,
        card_back: String,
        books: String,
        cars_info: Array<CarInfo>,
    ): ApiResponseNoData {

        val card_frontResponse = image_upload(card_front)


        if (!card_frontResponse.isSuccess()) {


            throw AppException(card_frontResponse.code, card_frontResponse.msg)
        }
        val card_backResponse = image_upload(card_back)

        if (!card_backResponse.isSuccess()) {
            throw AppException(card_backResponse.code, card_backResponse.msg)

        }
        val booksResponse = image_upload(books)

        if (!booksResponse.isSuccess()) {
            throw AppException(booksResponse.code, booksResponse.msg)

        }
        cars_info.map {
            image_upload(it.books)
        }.run {

            if (any { !it.isSuccess() }) {
                val first = first { !it.isSuccess() }
                throw AppException(first.code, first.msg)
            }

            cars_info.forEachIndexed { index, carInfo ->

                carInfo.books = get(index).data.url
            }

        }

        val hasMap = hashMapOf<String, String>()
        cars_info.forEachIndexed { index, carInfo ->
            hasMap.run {
                put("cars_info[$index][books]", carInfo.books)
                put("cars_info[$index][cars_type]", carInfo.cars_type)
                put("cars_info[$index][lengths]", carInfo.lengths)
                put("cars_info[$index][license]", carInfo.license)
                put("cars_info[$index][weights]", carInfo.weights)
            }

        }


        return apiService.driver_work(
            names,
            mobile,
            code,
            card_frontResponse.data.url,
            card_backResponse.data.url,
            booksResponse.data.url,
            hasMap, team_id
        )
    }

    //上传签名文件
    suspend fun sign_files(paths: Array<String>, id: Int): ApiResponseNoData {
        val urlResponses = paths.map {
            image_upload(it)
        }

        if (urlResponses.any { !it.isSuccess() }) {
            urlResponses.first { !it.isSuccess() }.run {

                throw AppException(code, msg)
            }
        }

        return apiService.sign_files(urlResponses.map { it.data.url }.toTypedArray(), id)
    }


    private suspend fun image_upload(path: String): ApiResponse<PictureUrl> {
        val file = FileUtils.getFileByPath(path)
//        val fileRQ = RequestBody.create(MediaType.parse("image/*"), file)
        val fileRQ = RequestBody.create(MediaType.parse("multipart/form-data"), file)
        val part = MultipartBody.Part.createFormData("picurl", file.name, fileRQ)
        return apiService.img_upload(part)
    }
}